#!/bin/bash
# 从第一行到最后一行分别表示：
# 1. 等待MySQL服务启动后再进行数据迁移。nc即netcat缩写
# 2. 收集静态文件到根目录static文件夹，
# 3. 生成数据库可执行文件，
# 4. 根据数据库可执行文件来修改数据库
# 5. 用 uwsgi启动 django 服务
# 6. tail空命令防止web容器执行脚本后退出
param_host=$(cat mars/config/host.yml | shyaml get-value database.host)
if [ -z "$param_host" ];then
    $param_host = 'db'
fi
echo $param_host

while ! nc -z $param_host 3306 ; do
    echo "Waiting for the MySQL Server"
    sleep 3
done
chmod -R 777 ./logs
chmod -R 775 ./wxmp
chmod +x resetpwd.sh
python manage.py collectstatic --noinput
python manage.py makemigrations --skip-checks &&
python manage.py migrate --skip-checks &&
python manage.py shell -c "from django.contrib.auth import get_user_model; User = get_user_model();  \
                           User.objects.filter(username='admin').exists() or \
                           User.objects.create_superuser('admin',
                           'admin@example.com', '123456')" 

# 执行自定义数据库初始化脚本
param_user=$(cat mars/config/host.yml | shyaml get-value database.user)
param_password=$(cat mars/config/host.yml | shyaml get-value database.password)
param_db=$(cat mars/config/host.yml | shyaml get-value database.db)

if [ -f "db_bak/init.sql" ]; then
    mysql -u$param_user -p$param_password -h$param_host  $param_db < db_bak/init.sql
    mv db_bak/init.sql db_bak/init_locked.sql
fi

chmod -R 775 ./mars/static
chmod -R 775 ./mars/media

#uwsgi --enable-threads --ini /var/www/html/mars/uwsgi.ini &&
supervisord -c supervisord.conf && 
echo "服务已启动！" && 
tail -f /dev/null

 
exec "$@"
